package map;

import java.util.HashMap;
import java.util.Map;

/**
 * 138. 复制带随机指针的链表
 */
public class CopyRandomList {
    public Node copyRandomList(Node head) {
        // 遍历原先节点存入map并创建复制的新节点
        Map<Node, Node> map = new HashMap<>();
        for (Node node = head; node != null; node = node.next) {
            map.put(node, new Node(node.val));
        }
        for (Node node = head; node != null; node = node.next) {
            map.get(node).next = map.get(node.next);
            map.get(node).random = map.get(node.random);
        }
        return map.get(head);
    }
}

class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}